package com.ruoyi.oto.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.MemberUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.oto.constants.*;
import com.ruoyi.oto.domain.*;
import com.ruoyi.oto.domain.dto.CompanyCheckDTO;
import com.ruoyi.oto.domain.dto.CompanyQuryDTO;
import com.ruoyi.oto.domain.dto.CompanyRegDTO;
import com.ruoyi.oto.mapper.CompanyCoreBakMapper;
import com.ruoyi.oto.mapper.CompanyCoreMapper;
import com.ruoyi.oto.service.BranchLinkService;
import com.ruoyi.oto.service.CompanyCoreService;
import com.ruoyi.oto.service.CompanyTagsService;
import com.ruoyi.oto.service.MemberUserService;
import com.ruoyi.oto.tagmatcher.TagMatcherNode;
import com.ruoyi.oto.tagmatcher.enums.TagMatcherNodeOpt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业服务
 *
 * @author ruoyi
 */
@Service
public class CompanyCoreServiceImpl extends ServiceImpl<CompanyCoreMapper, CompanyCore> implements CompanyCoreService
{
    @Autowired
    private CompanyTagsService companyTagsService;

    private BranchLinkService branchLinkService;
    @Autowired
    private MemberUserService memberUserService;

    /**
     * 分页查询列表
     * @param pageDTO
     * @return
     */
    @Override
    public IPage<CompanyCore> pageCompany(CompanyQuryDTO pageDTO) {
        IPage<CompanyCore> page = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        List<Long> companyIds = new ArrayList<>();
        List<String> conditions = new ArrayList<>();
        if(pageDTO.getTagValCond()!=null && !pageDTO.getTagValCond().isEmpty()){
            for(TagMatcherNode tagMatcherNode: pageDTO.getTagValCond()){
                TagMatcherNodeOpt nodeOpt = TagMatcherNodeOpt.getByDesc(tagMatcherNode.getOpt());
                String s = "tag_id = "+tagMatcherNode.getTagId()+" and tag_value "+nodeOpt.getCode()+" "+TagMatcherNodeOpt.spliceQueryCondition(nodeOpt, tagMatcherNode.getTagValue(), tagMatcherNode.getTagType());
                conditions.add("(" + s+" )");
            }
           companyIds = companyTagsService.getCompanyIdsByTagVal(conditions);
        }
        if(!conditions.isEmpty() && companyIds.isEmpty()){
            return page;
        }
        return this.page(page,new LambdaQueryWrapper<CompanyCore>()
                .like(StrUtil.isNotEmpty(pageDTO.getCompanyName()),CompanyCore::getCompanyName, pageDTO.getCompanyName())
                .eq(ObjUtil.isNotNull(pageDTO.getCompanyTypeId()),CompanyCore::getCompanyTypeId,pageDTO.getCompanyTypeId())
                .in(ObjUtil.isNotEmpty(companyIds),CompanyCore::getId,companyIds)
                .eq(ObjUtil.isNotNull(pageDTO.getStatus()),CompanyCore::getStatus,pageDTO.getStatus())
                .eq(ObjUtil.isNotNull(pageDTO.getShowFlag()),CompanyCore::getShowFlag,pageDTO.getShowFlag())
                .eq(CompanyCore::getDelFlag,DeleteFlag.NO)
                .orderByAsc(CompanyCore::getId));
    }

    /**
     * 企业注册
     * @param memberUser
     * @param regDTO
     * @return
     */
    @Override
    public Long regCompany(MemberUser memberUser, CompanyRegDTO regDTO) {
        if(regDTO.getCompanyId()==null){
            //企业新注册，判断可能的重复性
            CompanyCore companyCore = new CompanyCore();
            Integer count = companyCore.selectCount(new LambdaQueryWrapper<CompanyCore>().eq(CompanyCore::getStatus, CompanyStatus.审核通过)
                    .and(companyCoreLambdaQueryWrapper -> {
                        companyCoreLambdaQueryWrapper.eq(CompanyCore::getCompanyName, regDTO.getCompanyName()).or().eq(CompanyCore::getUniscid, regDTO.getUniscid());
                    }));
            if(count>0){
                throw new ServiceException("企业已经存在");
            }
        }
        CompanyCore companyCore = new CompanyCore();
        if(regDTO.getCompanyId()!=null){
            companyCore = this.getById(regDTO.getCompanyId());
            if(companyCore==null){
                throw new ServiceException("找不到企业数据");
            }
        }
        companyCore.setStatus(CompanyStatus.待审核状态);
        companyCore.setCompanyName(regDTO.getCompanyName());
        companyCore.setIntro(regDTO.getIntro());
        companyCore.setUniscid(regDTO.getUniscid());

        CompanyType companyType =  new CompanyType().selectById(regDTO.getCompanyTypeId());
        if(companyType==null){
            throw new ServiceException("企业类型不正确");
        }
        companyCore.setCompanyTypeId(regDTO.getCompanyTypeId());
        companyCore.setCompanyType(companyType.getTypeName());
        companyCore.setAddress(regDTO.getAddress());
        companyCore.setShowFlag(CompanyShowFlag.显示);
        companyCore.setContact(regDTO.getContact());
        companyCore.setContactPhone(regDTO.getContactPhone());
        companyCore.setMemberId(memberUser.getId());
        companyCore.setMemberName(memberUser.getUsername());
        if(companyCore.getId()==null){
            companyCore.setRegistType(0);
            companyCore.setCreateBy(memberUser.getUsername());
            companyCore.setCreateTime(new Date());
            companyCore.insert();
        }
        else{
            companyCore.setRegistType(1);
            companyCore.setUpdateBy(memberUser.getUsername());
            companyCore.setUpdateTime(new Date());
            companyCore.updateById();
        }
        return companyCore.getId();
    }

    /**
     * 编辑企业信息
     * @param loginUser
     * @param regDTO
     * @return
     */
    @Override
    public Long editCompany(LoginUser loginUser, CompanyRegDTO regDTO) {
        CompanyCore companyCore = null;
        if(loginUser.getUser()!=null && loginUser.getUser().isLogin()){
            companyCore = this.getById(regDTO.getCompanyId());
            if(companyCore==null){
                throw new ServiceException("企业不存在");
            }
        }
        else{
             companyCore = this.getOne(new LambdaQueryWrapper<CompanyCore>().eq(CompanyCore::getId,regDTO.getCompanyId())
                    .eq(CompanyCore::getMemberId,loginUser.getMember().getId()));
            if(companyCore==null){
                throw new ServiceException("企业不存在");
            }
            companyCore.setStatus(CompanyStatus.待审核状态);
        }
        companyCore.setCompanyName(regDTO.getCompanyName());
        companyCore.setIntro(regDTO.getIntro());
        companyCore.setUniscid(regDTO.getUniscid());
        CompanyType companyType =  new CompanyType().selectById(regDTO.getCompanyTypeId());
        if(companyType==null){
            throw new ServiceException("企业类型不正确");
        }
        companyCore.setCompanyTypeId(regDTO.getCompanyTypeId());
        companyCore.setCompanyType(companyType.getTypeName());
        companyCore.setAddress(regDTO.getAddress());
        companyCore.setShowFlag(CompanyShowFlag.显示);
        companyCore.setContact(regDTO.getContact());
        companyCore.setContactPhone(regDTO.getContactPhone());
        companyCore.updateById();
        return companyCore.getId();
    }

    /**
     * 删除企业
     * @param companyId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCompany(LoginUser loginUser,Long companyId) {
        CompanyCore company = this.getById(companyId);
        if(!loginUser.getUser().isAdmin()){
            throw new ServiceException("没有删除企业的权限");
        }
        if(company==null){
            throw new ServiceException("找不到对应的企业");
        }
        Long memberId = company.getMemberId();
        //删除企业
        company.setDelFlag(DeleteFlag.YES);
        company.setMemberId(null);
        company.setMemberName(null);
        this.updateById(company);
        //删除和联企人员的绑定关系
        branchLinkService.deleteAllByCompanyId(companyId);
        //将原来企业管理者绑定的微信用户删除
        memberUserService.removeById(memberId);
    }

    /**
     * 按绑定账号管理企业
     * @param memberId
     * @return
     */
    @Override
    public CompanyCore getCompanyByMemberId(Long memberId) {
        return this.getOne(new LambdaQueryWrapper<CompanyCore>().eq(CompanyCore::getMemberId, memberId).eq(CompanyCore::getDelFlag, DeleteFlag.NO));
    }

    /**
     * 后台审核企业
     * @param loginUser
     * @param checkDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long checkCompany(LoginUser loginUser,  CompanyCheckDTO checkDTO) {
        //获取当前待审核的企业
        CompanyCore companyCore = this.getOne(new LambdaQueryWrapper<CompanyCore>().eq(CompanyCore::getId, checkDTO.getCompanyId()).eq(CompanyCore::getStatus, CompanyStatus.待审核状态));
        if(ObjUtil.isNull(companyCore)){
            throw new ServiceException("待审核企业不存在");
        }
        if(checkDTO.getStatus()==CompanyStatus.审核通过){
            companyCore.setStatus(CompanyStatus.审核通过);
            companyCore.setShowFlag(CompanyShowFlag.显示);
            companyCore.setUpdateBy(loginUser.getUsername());
            companyCore.setUpdateTime(new Date());
            //删除历史上这家企业的非分
            CompanyCoreBak companyCoreBak = new CompanyCoreBak();
            companyCoreBak.deleteById(companyCore.getId());
            this.saveOrUpdate(companyCore);
            //改变当前对应的小程序用户为企业用户
            MemberUser memberUser = new MemberUser();
            memberUser = memberUser.selectById(companyCore.getMemberId());
            memberUser.setRoleId(MemberRoleConstant.企业用户);
            memberUser.setRoleName("企业用户");
            memberUser.setUpdateBy(loginUser.getUsername());
            memberUser.setUpdateTime(new Date());
            memberUser.updateById();
            return companyCore.getId();

        }
        else if(checkDTO.getStatus()==CompanyStatus.审核不通过){
            //删除自己并还原
            companyCore.deleteById(companyCore.getId());
            CompanyCoreBak companyCoreBak = new CompanyCoreBak();
            companyCoreBak = companyCoreBak.selectById(companyCore.getId());
            if(ObjUtil.isNotNull(companyCoreBak)){
                BeanUtils.copyProperties(companyCoreBak,companyCore );
                companyCore.insert();
            }
            return companyCore.getId();
        }
        throw new ServiceException("审核状态不正确");
    }

    /**
     * 我联络的企业
     * @param loginUser
     * @return
     */
    @Override
    public List<CompanyCore> myContactCompany(LoginUser loginUser) {
        Long memberId = loginUser.getMember().getId();
        return this.getBaseMapper().myContactCompany(memberId);
    }
}
